﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
using NET4.Database;

namespace NET4.Programma
{
  public partial class Settings : Form
  {
    public Settings()
    {
      InitializeComponent();
    }

    #region Protected methods
    protected void Init()
    {
      this.txtSiteAddress.Text = ConfigurationManager.AppSettings["WebsiteUrl"].ToString();
      this.txtSmtpAddress.Text = ConfigurationManager.AppSettings["SmtpAddress"].ToString();
      this.txtSmtpPort.Text = ConfigurationManager.AppSettings["SmtpPort"].ToString();
      this.txtSmtpUsername.Text = ConfigurationManager.AppSettings["SmtpUser"].ToString();

      String smtpPassword = ConfigurationManager.AppSettings["SmtpPassword"].ToString();

      if (smtpPassword != String.Empty)
      {
        this.txtSmtpPassword.Text = AES.Decrypt(HttpUtility.UrlDecode(smtpPassword), "net4");
      }
    }

    protected void Save()
    {
      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      config.AppSettings.Settings["WebsiteUrl"].Value = this.txtSiteAddress.Text;
      config.AppSettings.Settings["SmtpAddress"].Value = this.txtSmtpAddress.Text;
      config.AppSettings.Settings["SmtpPort"].Value = this.txtSmtpPort.Text;
      config.AppSettings.Settings["SmtpUser"].Value = this.txtSmtpUsername.Text;

      if (this.txtSmtpPassword.Text != String.Empty)
      {
        config.AppSettings.Settings["SmtpPassword"].Value = HttpUtility.UrlEncode(AES.Encrypt(this.txtSmtpPassword.Text, "net4")); ;
      }
      
      config.Save(ConfigurationSaveMode.Modified);
      ConfigurationManager.RefreshSection("appSettings");
    }
    #endregion

    #region EventHandlers
    private void Settings_Load(object sender, EventArgs e)
    {
      this.Init();
    }
    #endregion

    private void btnSave_Click(object sender, EventArgs e)
    {
      this.Save();

      this.Close();
    }
  }
}
